﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Web.UI.WebControls;
using Controllerss;
using Core.Contract.DataContract;
using www.Controllers;
using www.Controllerss;
using www.Core.Contract.DataContract;

namespace www.Admin
{
    public partial class Advertise : System.Web.UI.Page
    {
        #region Value
        //private readonly HyServicesClient _service1 = new HyServicesClient();
        private readonly AdvertiseController _advertiseControllers = new AdvertiseController();
        private readonly LanguageController _languageController=new LanguageController();
        private readonly ObjectCache _cache = MemoryCache.Default;
        static bool _insert = false;
        static int _id = 0;
        #endregion

        #region Contructor

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Convert.ToInt32(Session["role"]) != 1 && Convert.ToInt32(Session["role"]) != 2)
            {
                Message("Bạn không đủ quyền để thực hiện chức năng này.");
                Response.Redirect("Default.aspx");
            }
            if (Cache["Language"] == null)
            {
                var lLanguage = _languageController.GetLanguageDataContracts();
                if (lLanguage.Any())
                    Cache.Insert("Language", lLanguage.ToList(), null, DateTime.MaxValue, TimeSpan.FromDays(30));
            }

            if (!IsPostBack)
            {

                string[] arr = { "1,Banner", "2,Sidebar top", "3,Sidebar bottom", "4,Footer" };
                Utilities.Dropdownlists.Addlist(ddlgroups, arr, "vi-VN");
                Utilities.Dropdownlists.Addlist(ddltype_advertise, arr, "vi-VN");
                string[] arr1 = { "_self,_self", "_blank,_blank", "_parent,_parent", "_search,_search", "_top,_top" };
                Utilities.Dropdownlists.Addlist(ddltype_link, arr1, "vi-VN");
                var lLanguages = (List<RelaxLanguageDataContract>)Cache["Language"];
                if (lLanguages != null)
                {
                    var lReturn = lLanguages.Where(l => l.Type == 1);
                    Addlist(lReturn);
                }


            }

        }
        #endregion

        #region Event
        protected void ddlgroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }
        protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }
        protected void lbtinsert_Click(object sender, EventArgs e)
        {
            pnviews.Visible = false;
            pncontrols.Visible = true;
            Donew();
            _insert = true;
            _id = 0;
        }

        protected void lbtback_Click(object sender, EventArgs e)
        {
            try
            {
                Back();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtrefresh_Click(object sender, EventArgs e)
        {
            try
            {
                LoadData();
            }
            catch (Exception)
            {

            }

        }

        protected void lbtdel_Click(object sender, EventArgs e)
        {
            try
            {
                Delete();
            }
            catch (Exception)
            {

            }

        }

        protected void grid_advertise_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            try
            {
                grid_advertise.PageIndex = e.NewPageIndex;
                LoadData();
            }
            catch (Exception)
            {

            }
        }
        protected void ddlgroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadData();
        }

        protected void grid_advertise_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                _id = Convert.ToInt32(e.CommandArgument.ToString());
                var lData = (List<RelaxAdvertiseDataContract>)_cache["Advertise"];
                if (lData == null)
                    return;
                var first = lData.FirstOrDefault(p => p.Id == _id && p.Languagecode == Convert.ToInt32(ddlLanguage1.SelectedValue));
                if (first == null)
                    return;
                if (e.CommandName == "cmd_edit")
                {

                    txtname.Value = first.Name;
                    fuadvertise.ResolveUrl(first.Image);
                    //txtwidth.Text = dt.Rows[0][3].ToString();
                    //txtheight.Text = dt.Rows[0][4].ToString();
                    txtlink.Value = first.Link;

                    txtdecription.Value = first.Decription;

                    ddltype_advertise.Value = first.Type.ToString();
                    ddltype_link.Value = first.Target;
                    txtord.Value = first.Ord.ToString();
                    txtDateBegin.Text = first.FromDate.ToShortDateString();
                    txtDateEnd.Text = first.ToDate.ToShortDateString();
                    txtprice.Value = String.Format("{0:#,##0}", first.Price);
                    chkactive.Checked = first.Active == 1;
                    ddlLanguage.Value = first.Languagecode.ToString();
                    pncontrols.Visible = true;
                    pnviews.Visible = false;
                    _insert = false;

                }
                else if (e.CommandName == "cmd_delete")
                {
                    DeleteLanguage(Convert.ToInt32(Session["LanguageCode"]));
                    Utilities.DeleteFile(Server.MapPath("~/" + first.Image));
                    lData.Remove(first);
                    _cache["Advertise"] = lData;
                    LoadData();
                    Message("Xóa Thành Công");
                    _id = 0;

                }
                else if (e.CommandName == "cmd_active")
                {
                    first.Active = first.Active == 1 ? 0 : 1;

                    _advertiseControllers.Update(new List<RelaxAdvertiseDataContract> { first });
                    _cache["Advertise"] = lData;
                    LoadData();
                    Message("Cập nhật Thành Công");

                    _id = 0;

                }
            }
            catch (Exception)
            {

            }
        }


        protected void lbtsave_Click(object sender, EventArgs e)
        {
            try
            {
                Save();
            }
            catch (Exception)
            {

            }
        }

        protected void lbtdonew_Click(object sender, EventArgs e)
        {
            try
            {
                Donew();
            }
            catch (Exception)
            {

            }

        }

        #endregion

        #region Business


        private void Addlist(IEnumerable<RelaxLanguageDataContract> lLanguageDataContracts)
        {
            ddlLanguage1.Items.Clear();
            ddlLanguage1.Items.Add(new ListItem("--Chọn--", "0"));
            ddlLanguage.Items.Clear();
            ddlLanguage.Items.Add(new ListItem("--Chọn--", "0"));
            foreach (var item in lLanguageDataContracts)
            {
                ddlLanguage.Items.Add(new ListItem(item.Name, item.Id.ToString()));
                ddlLanguage1.Items.Add(new ListItem(item.Name, item.Id.ToString()));
            }

        }
        //private void InsertLanguageCode(IEnumerable<RelaxAdvertiseDataContract> lData, int iD = 0)
        //{

        //    if (!string.IsNullOrEmpty(ddlLanguage.Value))
        //    {
        //        var path = "Images/Advertise/";
        //        var postedfile = fuadvertiseValue.PostedFile;
        //        if (postedfile != null)
        //        {
        //            var filename = path + postedfile.FileName;
        //            if (iD > 0)
        //            {
        //                if (LAdvertiseValue == null)
        //                {
        //                    if (lData != null)
        //                    {
        //                        var lVaue =
        //                            lData.Where(
        //                                p => p.Id == iD && p.Languagecode != Convert.ToInt32(Session["LanguageCode"]))
        //                                .ToList();
        //                        if (!lVaue.Any())
        //                            lVaue = new List<RelaxAdvertiseDataContract>();
        //                        LAdvertiseValue = lVaue;
        //                    }
        //                    else
        //                        LAdvertiseValue = new List<RelaxAdvertiseDataContract>();
        //                }

        //                var languageCode = Convert.ToInt32(ddlLanguage.Value);
        //                var check = LAdvertiseValue.Where(p => p.Languagecode == languageCode).ToList();
        //                if (check.Any())
        //                {
        //                    if (insertNew)
        //                    {
        //                        var firstordefault = check.FirstOrDefault();
        //                        if (firstordefault != null)
        //                        {
        //                            firstordefault.Languagecode = languageCode;
        //                            firstordefault.Name = txtName_Value.Value;
        //                            firstordefault.Decription = txtdecription_value.Value;
        //                            firstordefault.Link = txtlink_Value.Value;
        //                            firstordefault.Target = ddltype_link_Value.Value;
        //                            var tmpmon = txtprice_Value.Value.Split(',');
        //                            var monney = tmpmon.Aggregate("", (current, s) => current + s);
        //                            firstordefault.Active = chkActiveValue.Checked ? 1 : 0;
        //                            firstordefault.Price = Convert.ToDouble(monney);
        //                            firstordefault.FromDate = Convert.ToDateTime(txtDateBegin_Value.Text);
        //                            firstordefault.ToDate = Convert.ToDateTime(txtDateEnd_Value.Text);
        //                            var img = firstordefault.Image;
        //                            if (!string.IsNullOrEmpty(postedfile.FileName))
        //                            {
        //                                Utilities.DeleteFile(Server.MapPath("~/"+img));
        //                                firstordefault.Image = filename;
        //                                postedfile.SaveAs(Server.MapPath("~/" + filename));
        //                            }
        //                        }
        //                    }
        //                    else
        //                    {
        //                        Message("Ngôn ngữ này đã tồn tại.");
        //                        return;
        //                    }
        //                }
        //                else
        //                {
        //                    if (string.IsNullOrEmpty(postedfile.FileName))
        //                    {
        //                        Message("Hình Ảnh không được để trống.");
        //                        return;
        //                    }
        //                    var tmpmon = txtprice_Value.Value.Split(',');

        //                    var monney = tmpmon.Aggregate("", (current, s) => current + s);

        //                    var advertise = new RelaxAdvertiseDataContract
        //                    {
        //                        Languagecode = languageCode,
        //                        Name = txtName_Value.Value,
        //                        Decription = txtdecription_value.Value,
        //                        Link = txtlink.Value,
        //                        Target = ddltype_link.Value,
        //                        Type = Convert.ToInt32(ddltype_advertise.Value),
        //                        FromDate = Convert.ToDateTime(txtDateBegin.Text),
        //                        ToDate = Convert.ToDateTime(txtDateEnd.Text),
        //                        Price = Convert.ToDouble(monney ?? "0"),
        //                        Active = chkActiveValue.Checked ? 1 : 0,
        //                        Image = filename
        //                    };

        //                    LAdvertiseValue.Add(advertise);
        //                    postedfile.SaveAs(Server.MapPath("~/" + filename));
        //                }
        //            }
        //            else
        //            {
        //                if (LAdvertiseValue == null)
        //                    LAdvertiseValue = new List<RelaxAdvertiseDataContract>();

        //                var languageCode = Convert.ToInt32(ddlLanguage.Value);
        //                var check = LAdvertiseValue.Where(p => p.Languagecode == languageCode).ToList();
        //                if (check.Any())
        //                {
        //                    if (insertNew)
        //                    {
        //                        var firstordefault = check.FirstOrDefault();
        //                        if (firstordefault != null)
        //                        {
        //                            firstordefault.Languagecode = languageCode;
        //                            firstordefault.Name = txtName_Value.Value;
        //                            firstordefault.Decription = txtdecription_value.Value;
        //                            firstordefault.Link = txtlink_Value.Value;
        //                            firstordefault.Target = ddltype_link_Value.Value;
        //                            var tmpmon = txtprice_Value.Value.Split(',');
        //                            var monney = tmpmon.Aggregate("", (current, s) => current + s);
        //                            firstordefault.Active = chkActiveValue.Checked ? 1 : 0;
        //                            firstordefault.Price = Convert.ToDouble(monney);
        //                            firstordefault.FromDate = Convert.ToDateTime(txtDateBegin_Value.Text);
        //                            firstordefault.ToDate = Convert.ToDateTime(txtDateEnd_Value.Text);
        //                            var img = firstordefault.Image;
        //                            if (!string.IsNullOrEmpty(postedfile.FileName))
        //                            {
        //                                Utilities.DeleteFile(Server.MapPath("~/" + img));
        //                                firstordefault.Image = filename;
        //                                postedfile.SaveAs(Server.MapPath("~/" + filename));
        //                            }
        //                        }
        //                    }
        //                    else
        //                    {
        //                        Message("Ngôn ngữ này đã tồn tại.");
        //                        return;
        //                    }
        //                }
        //                else
        //                {
        //                    if (string.IsNullOrEmpty(postedfile.FileName))
        //                    {
        //                        Message("Hình Ảnh không được để trống.");
        //                        return;
        //                    }

        //                    var tmpmon = txtprice_Value.Value.Split(',');

        //                    var monney = tmpmon.Aggregate("", (current, s) => current + s);

        //                    var advertise = new RelaxAdvertiseDataContract
        //                    {
        //                        Languagecode = languageCode,
        //                        Name = txtName_Value.Value,
        //                        Decription = txtdecription_value.Value,
        //                        Link = txtlink.Value,
        //                        Target = ddltype_link.Value,
        //                        Type = Convert.ToInt32(ddltype_advertise.Value),
        //                        FromDate = Convert.ToDateTime(txtDateBegin.Text),
        //                        ToDate = Convert.ToDateTime(txtDateEnd.Text),
        //                        Price = Convert.ToDouble(monney ?? "0"),
        //                        Active = chkActiveValue.Checked ? 1 : 0,
        //                        Image = filename
        //                    };
        //                    LAdvertiseValue.Add(advertise);
        //                    postedfile.SaveAs(Server.MapPath("~/" + filename));
        //                }
        //            }
        //        }
        //        else
        //        {
        //            Message("Hình Ảnh không được để trống.");
        //        }
        //        grvNgonngu.DataSource = LAdvertiseValue;
        //        grvNgonngu.DataBind();

        //    }
        //    else
        //    {
        //        Message("Bạn phải chọn ngôn ngữ.");
        //    }
        //}

        //private void EditLanguage(int iLanguageCode)
        //{
        //    if (iLanguageCode <= 0) return;
        //    var first = LAdvertiseValue.FirstOrDefault(p => p.Languagecode == iLanguageCode);
        //    if (first != null)
        //    {
        //        txtName_Value.Value = first.Name;
        //        txtdecription_value.Value = first.Decription;
        //        ddlLanguage.Value = first.Languagecode.ToString();
        //        txtDateBegin_Value.Text = first.FromDate.ToShortDateString();
        //        txtDateEnd_Value.Text = first.ToDate.ToShortDateString();
        //        txtprice_Value.Value = String.Format("{0:#,##0}", first.Price);
        //        txtlink_Value.Value = first.Link;
        //        ddltype_link_Value.Value = first.Target;
        //        chkActiveValue.Checked = first.Active == 1;
        //    }
        //}
        private void DeleteLanguage(int iLanguageCode)
        {
            if (iLanguageCode <= 0) return;

            if (_id > 0)
            {
                _advertiseControllers.Delete(new List<long> { _id }, iLanguageCode);

            }
        }
        private void Save()
        {
            try
            {
                if (string.IsNullOrEmpty(txtlink.Value) || string.IsNullOrEmpty(txtname.Value) ||
                    string.IsNullOrEmpty(txtord.Value) || string.IsNullOrEmpty(txtdecription.Value) ||
                    string.IsNullOrEmpty(ddltype_advertise.Value) || Convert.ToInt32(ddlLanguage.Value) <= 0)
                {
                    Message("Bạn phải nhập đầy đủ thông tin gợi ý trên");
                    return;
                }
                var lData = (List<RelaxAdvertiseDataContract>)_cache["Advertise"];

                //if (Utilities.Helper.IsValidUrl(txtlink.Value))
                //{
                var path = "Images/Advertise/";
                var ac = chkactive.Checked ? 1 : 0;
                var postedfile = fuadvertise.PostedFile;//Request.Files["fuadvertise"];
                if (postedfile != null)
                {
                    var filename = postedfile.FileName;
                    if (!_insert)
                    {
                        var lUpdate = new List<RelaxAdvertiseDataContract>();
                        if (lData == null)
                            return;
                        var first =
                            lData.FirstOrDefault(
                                p => p.Id == _id && p.Languagecode == Convert.ToInt32(ddlLanguage.Value));
                        if (first == null)
                            return;
                        var img = first.Image;
                        if (string.IsNullOrEmpty(filename))
                            path = first.Image;
                        else
                            path += filename;

                        var tmpmon = txtprice.Value.Split(',');

                        var monney = tmpmon.Aggregate("", (current, s) => current + s);

                        var advertise = new RelaxAdvertiseDataContract
                        {
                            Id = _id,
                            Active = ac,
                            Link = txtlink.Value,
                            Ord = string.IsNullOrEmpty(txtord.Value) ? 0 : Convert.ToInt32(txtord.Value),
                            Target = ddltype_link.Value,
                            Type = Convert.ToInt32(ddltype_advertise.Value),
                            Image = path,
                            Name = txtname.Value,
                            Decription = txtdecription.Value,
                            Languagecode = Convert.ToInt32(ddlLanguage.Value),
                            FromDate = Convert.ToDateTime(txtDateBegin.Text),
                            ToDate = Convert.ToDateTime(txtDateEnd.Text),
                            Price = Convert.ToDouble(monney ?? "0")
                        };
                        lUpdate.Add(advertise);
                        
                        if (_advertiseControllers.Update(lUpdate))
                        {
                            if (!string.IsNullOrEmpty(filename))
                            {
                                Utilities.DeleteFile(Server.MapPath("~/" + img));
                                postedfile.SaveAs(Server.MapPath("~/" + path));
                            }
                            foreach (var item in lUpdate)
                            {
                                var firstordefault = lData.FirstOrDefault(p => p.Id == item.Id && p.Languagecode == item.Languagecode);
                                if (firstordefault != null)
                                {
                                    firstordefault.Name = item.Name;
                                    firstordefault.Image = item.Image;
                                    firstordefault.Link = item.Link;
                                    firstordefault.Ord = lUpdate[0].Ord;
                                    firstordefault.Target = item.Target;
                                    firstordefault.Type = lUpdate[0].Type;
                                    firstordefault.Decription = item.Decription;
                                    firstordefault.Active = item.Active;
                                    firstordefault.Price = item.Price;
                                    firstordefault.FromDate = item.FromDate;
                                    firstordefault.ToDate = item.ToDate;
                                    firstordefault.Active = item.Active;
                                }
                            }

                            _cache["Advertise"] = lData;
                            Message("Sửa Thành Công !");
                            _id = 0;
                            pncontrols.Visible = false;
                            pnviews.Visible = true;
                        }
                    }
                    else
                    {
                        if (string.IsNullOrEmpty(filename))
                        {
                            Message("Ảnh không được bỏ trống.");
                            return;
                        }
                        var tmpmon = txtprice.Value.Split(',');

                        var monney = tmpmon.Aggregate("", (current, s) => current + s);
                        path += filename;
                        var lAdd = new List<RelaxAdvertiseDataContract>();
                        var advertise = new RelaxAdvertiseDataContract
                        {
                            Id = _id,
                            Active = ac,
                            Link = txtlink.Value,
                            Ord = string.IsNullOrEmpty(txtord.Value) ? 0 : Convert.ToInt32(txtord.Value),
                            Target = ddltype_link.Value,
                            Type = Convert.ToInt32(ddltype_advertise.Value),
                            Image = path,
                            Name = txtname.Value,
                            Decription = txtdecription.Value,
                            Languagecode = Convert.ToInt32(ddlLanguage.Value),
                            FromDate = Convert.ToDateTime(txtDateBegin.Text),
                            ToDate = Convert.ToDateTime(txtDateEnd.Text),
                            Price = Convert.ToDouble(monney)
                        };

                        lAdd.Add(advertise);

                        var lId = _advertiseControllers.Add(lAdd);
                        foreach (var item in lAdd)
                        {
                            item.Id = lId;
                        }

                        if (lData == null)
                            lData = new List<RelaxAdvertiseDataContract>();
                        lData.AddRange(lAdd);
                        _cache["Advertise"] = lData;
                        postedfile.SaveAs(Server.MapPath("~/" + path));
                        Message("Thêm Thành Công !");
                    }
                }
                else
                {
                    Message("Bạn phải chọn ảnh !");
                }
                //}
                //else
                //{
                //    Message("Bạn Nhập Sai link liên kết. <br />VD: http://www.dantri.com.vn");
                //}
            }
            catch (Exception ex)
            {
                Message(ex.Message);
            }
        }
        private void Back()
        {
            pnviews.Visible = true;
            pncontrols.Visible = false;
            _insert = false;
            _id = 0;
            LoadData();
        }
        private void FilterAdvertise(List<RelaxAdvertiseDataContract> lAdvertiseDataContracts)
        {
            if (lAdvertiseDataContracts == null)
                return;
            var tmp = lAdvertiseDataContracts.ToList();
            foreach (var item in tmp)
            {
                var checkItem = lAdvertiseDataContracts.Where(p => p.Id == item.Id).ToList();
                if (checkItem.Count > 1)
                {
                    var first = checkItem.FirstOrDefault();
                    foreach (var item1 in checkItem)
                    {
                        lAdvertiseDataContracts.Remove(item1);
                    }
                    lAdvertiseDataContracts.Add(first);
                }
            }
        }
        private void Delete()
        {
            try
            {
                if (grid_advertise.Rows.Count <= 0) return;
                var hang = 0;
                var lAd = new List<long>();
                for (var i = 0; i < grid_advertise.Rows.Count; ++i)
                {
                    var chkselect = ((CheckBox)grid_advertise.Rows[i].FindControl("chkselect")).Checked;
                    if (chkselect)
                    {
                        var id = ((Label)grid_advertise.Rows[i].FindControl("lblid")).Text;
                        lAd.Add(Convert.ToInt32(id));
                    }
                }
                _advertiseControllers.Delete(lAd, Convert.ToInt32(Session["LanguageCode"]));
                var lData = (List<RelaxAdvertiseDataContract>)_cache["Advertise"];
                if ((lData.Any()))
                {
                    foreach (var id in lAd)
                    {
                        var first = lData.FirstOrDefault(p => p.Id == id);
                        if (first != null)
                            lData.Remove(first);
                        hang++;
                    }

                }

                if (hang != 0)
                {
                    Message("Có " + hang + "bản ghi được Xóa Thành Công");
                }
                else
                {
                    Message("Không có bản ghi nào được xóa !");

                }
                LoadData();
            }
            catch { }
        }
        public void LoadData()
        {
            if (_cache["Advertise"] == null)
            {
                var lData = _advertiseControllers.GetAdvertiseDataContracts();
                if (lData != null)
                {
                    var policy = new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(1) };
                    _cache.Set("Advertise", lData.ToList(), policy);
                    var lReturn =
                        (from a in
                             lData.Where(
                                 p =>
                                     p.Type == Convert.ToInt32(ddlgroups.SelectedValue) &&
                                     p.Languagecode == Convert.ToInt32(ddlLanguage1.SelectedValue))
                         select new RelaxAdvertiseDataContract { Active = a.Active, Decription = a.Decription, Id = a.Id, Image = a.Image, Languagecode = a.Languagecode, Link = a.Link, Name = a.Name, Ord = a.Ord, Target = a.Target, Type = a.Type, FromDate = a.FromDate, ToDate = a.ToDate, Price = a.Price }).ToList();
                    FilterAdvertise(lReturn);
                    grid_advertise.DataSource = lReturn.ToList();
                    grid_advertise.DataBind();
                }
            }
            else
            {
                var lData = (List<RelaxAdvertiseDataContract>)_cache["Advertise"];
                var lReturn =
                        (from a in
                             lData.Where(
                                 p =>
                                     p.Type == Convert.ToInt32(ddlgroups.SelectedValue) &&
                                     p.Languagecode == Convert.ToInt32(ddlLanguage1.SelectedValue))
                         select new RelaxAdvertiseDataContract { Active = a.Active, Decription = a.Decription, Id = a.Id, Image = a.Image, Languagecode = a.Languagecode, Link = a.Link, Name = a.Name, Ord = a.Ord, Target = a.Target, Type = a.Type, FromDate = a.FromDate, ToDate = a.ToDate, Price = a.Price }).ToList();
                FilterAdvertise(lReturn);
                grid_advertise.DataSource = lReturn.ToList();
                grid_advertise.DataBind();

            }
        }


        private void Donew()
        {
            chkactive.Checked = false;
            txtdecription.Value = "";
            txtname.Value = "";
            txtlink.Value = "";
            txtord.Value = "";
            txtname.Focus();
        }
        private void Message(string str)
        {
            Response.Write("<script>alert('" + str + "');</script>");
        }
        #endregion
    }
}